{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import operator"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def creatDataSet():\n",
    "    group = np.array([[1.0,1.1],[1.0,1.0],[0,0],[0,0.1]])\n",
    "    labels = ['A','A','B','B']\n",
    "    return group, labels"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def classify(inX, dataSet, labels, k):\n",
    "    dataSetSize = dataSet.shape[0]\n",
    "    #dataSetSize = np.shape(dataSet)[0]\n",
    "    #dataSetSize = len(dataSet)\n",
    "    diffMat = np.tile(inX,(dataSetSize,1)) - dataSet\n",
    "    sqDiffMat = diffMat **2\n",
    "    sqDistances = sqDiffMat.sum(axis = 1)\n",
    "    distances = sqDistances ** 0.5\n",
    "    sortedDistances = distances.argsort()\n",
    "    classCount = {}\n",
    "    for i in range(k):\n",
    "        voteIlabel = labels[sortedDistances[i]]\n",
    "        classCount[voteIlabel] = classCount.get(voteIlabel,0) +1\n",
    "    sortedClassCount = sorted(classCount.items(), key = operator.itemgetter(1), reverse = True)\n",
    "    return sortedClassCount[0][0]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'A'"
      ]
     },
     "execution_count": 17,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "group,labels = creatDataSet()\n",
    "classify([1,1],group,labels,3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.1"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
